package com.primaryedu.ui.sign;

import java.util.HashMap;
import java.util.Map;

import org.json.JSONException;
import org.json.JSONObject;

import android.content.Intent;
import android.graphics.SweepGradient;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.ZoomControls;

import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.mapapi.BMapManager;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.MapStatusUpdate;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.MyLocationData;
import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.model.inner.GeoPoint;
import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.primaryedu.R;
import com.primaryedu.bean.SignBean;
import com.primaryedu.data.Contants;
import com.primaryedu.data.GlobalData;
import com.primaryedu.ui.BaseActivity;
import com.primaryedu.utils.Utils;
import com.primaryedu.widget.CircularImage;

/**
 * 签到窗体界面
 *
 * @author jun.wang
 * @description
 * @data 2016年12月20日
 */
public class SignActivity extends BaseActivity implements OnClickListener {
    private TextView text_right;
    private TextView text_address, text_state;
    MapView mMapView;
    BaiduMap mBaiduMap;
    boolean isFirstLoc = true;// 是否首次定位
    boolean isOk = false;// 是否首次定位
    public BMapManager mapManager;
    // 定位相关
    LocationClient mLocClient;
    public MyLocationListenner myListener = new MyLocationListenner();
    private boolean isMobile = true;
    private double lng_two;      // 当前经纬度
    private double lat_two;

    private Handler handler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 1001:
                    text_state.setText("不在签到范围内          切换校区");
                    text_address.setText(GlobalData.loc_address);
                    break;

                case 1002:
                    text_state.setText("可以签到");
                    text_address.setText(GlobalData.loc_address);
                    break;

                case 1003:
                    state = signBean.getStatus();
                    if (signBean.getStatus().equals("1")) {
                        text_state.setText("已签到");
                        text_time.setText("签到时间:" + signBean.getSigntime());
                        text_sign_address.setText(signBean.getAddress());
                    } else {
                        text_time.setText("未签到");
                        text_sign_address.setVisibility(View.INVISIBLE);
                    }
                    break;

                default:
                    break;
            }
        }

        ;
    };

    private CircularImage headImage;
//    LoadImage loadImage;
    private TextView text_name, text_time, text_sign_address;
    SignBean signBean;
    private String state = "0";  // 1已签到   0未签到

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
//        setContentView(R.layout.activity_sign);

        init();
    }

    private void init() {
//        loadImage = LoadImage.getInstance();
        ((TextView) findViewById(R.id.title)).setText("签到");
        findViewById(R.id.back).setOnClickListener(this);
        findViewById(R.id.right).setVisibility(View.VISIBLE);
        findViewById(R.id.right).setOnClickListener(this);
        text_right = (TextView) findViewById(R.id.text_right);
        text_right.setText("签到");
        text_right.setTextColor(getResources().getColor(R.color.main_button));
        text_address = (TextView) this.findViewById(R.id.text_address);
        text_address.setText(GlobalData.loc_address);
        text_state = (TextView) this.findViewById(R.id.text_state);
        text_state.setOnClickListener(this);
        headImage = (CircularImage) this.findViewById(R.id.headImage);
        text_name = (TextView) this.findViewById(R.id.text_name);
        text_time = (TextView) this.findViewById(R.id.text_time);
        text_sign_address = (TextView) this.findViewById(R.id.text_sign_address);

        System.out.println("GlobalData====" + GlobalData.accountBean);
//        headImage.setTag(GlobalData.getUserphotourl(getApplicationContext()));
        Glide.with(this)
                .load(GlobalData.getUserphotourl(getApplicationContext()))
                .placeholder(R.drawable.default_error)
                .error(R.drawable.default_error)
                .centerCrop()
                .crossFade()
                .into(headImage);
//        loadImage.addTask(GlobalData.getUserphotourl(getApplicationContext()), headImage);
//        loadImage.doTask();
        text_name.setText(GlobalData.getUserNickname(getApplicationContext()));
        text_time.setText(Utils.getCurrentDateTwo());
        signBean = new SignBean();

        initMap();

    }

    @Override
    protected int BindLayout() {
        return R.layout.activity_sign;
    }

    @Override
    protected void initView() {

    }

    @Override
    protected void initData() {

    }

    private void initMap() {
        // 地图初始化
        mMapView = (MapView) findViewById(R.id.bmapView);

        mBaiduMap = mMapView.getMap();
        // 开启定位图层
        mBaiduMap.setMyLocationEnabled(true);
        mBaiduMap.setBuildingsEnabled(true);
        mBaiduMap.setTrafficEnabled(true);

        // 定位初始化
        mLocClient = new LocationClient(this);

        mLocClient.registerLocationListener(myListener);
        LocationClientOption option = new LocationClientOption();
        option.setOpenGps(true);         // 打开gps
        option.setCoorType("bd09ll");     // 设置坐标类型
        option.setScanSpan(1000);

        option.setIsNeedAddress(true);   //可选，设置是否需要地址信息，默认不需要
        option.setIsNeedLocationDescribe(true);
        option.setEnableSimulateGps(true);
        option.setIgnoreKillProcess(true);
        option.setLocationNotify(true);
        option.setOpenGps(true);
        option.setEnableSimulateGps(true);
        option.setIsNeedLocationDescribe(true);
        option.setNeedDeviceDirect(true);

        mLocClient.setLocOption(option);
        mLocClient.start();

        // 隐藏百度logo
        View child = mMapView.getChildAt(1);
        if (child != null && (child instanceof ImageView || child instanceof ZoomControls)) {
            child.setVisibility(View.INVISIBLE);
        }

        requestData();

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.back:
                finish();
                break;

            case R.id.right:
                if (isOk) {

                    if (state.equals("1")) {
                        showToast("今天您已经签到了!");
                    } else {
                        commitData();
                    }

                } else {
                    showToast("不在签到范围内!");
                }

//			 commitData() ;
                break;

            case R.id.text_state:
                Intent intent = new Intent(SignActivity.this, SignActivityTwo.class);
                startActivity(intent);
                finish();
                break;

            default:
                break;
        }
    }

    /**
     * 定位SDK监听函数
     */
    public class MyLocationListenner implements BDLocationListener {

        @Override
        public void onReceiveLocation(BDLocation location) {
            // map view 销毁后不在处理新接收的位置
            if (location == null || mMapView == null) {
                return;
            }
            MyLocationData locData = new MyLocationData.Builder()
                    .accuracy(0)
                    // 此处设置开发者获取到的方向信息，顺时针0-360
                    .direction(100).latitude(location.getLatitude())
                    .longitude(location.getLongitude()).build();

            lng_two = locData.longitude;
            lat_two = locData.latitude;

            uplateAddress();

            // TODO
            mBaiduMap.setMyLocationData(locData);
            if (isFirstLoc) {
                isFirstLoc = false;
                LatLng ll = new LatLng(location.getLatitude(),
                        location.getLongitude());

                float f = mBaiduMap.getMaxZoomLevel(); //19.0
                MapStatusUpdate u = MapStatusUpdateFactory.newLatLngZoom(ll, f - 2);
                mBaiduMap.animateMapStatus(u);
            }

            GeoPoint pt = new GeoPoint((int) (location.getLatitude() * 1e6),
                    (int) (location.getLongitude() * 1e6));

        }

        public void onReceivePoi(BDLocation poiLocation) {

        }
    }

    private void uplateAddress() {
        double temp = Utils.GetShortDistance(lng_two, lat_two, GlobalData.nanjingHightlng, GlobalData.nanjingHightlat);
        System.out.println("temp===" + temp);

        if (temp < 1500) {
            isOk = true;
            handler.sendEmptyMessage(1002);
        } else {
            isOk = false;
            handler.sendEmptyMessage(1001);
        }
    }

    private void requestData() {
        StringBuilder builder = new StringBuilder();
        builder.append(Contants.getSign);
        builder.append("?userid=").append(GlobalData.getUserId(SignActivity.this));

        StringRequest stringRequest = new StringRequest(Request.Method.GET,
                builder.toString(), new Response.Listener<String>() {
            @Override
            public void onResponse(String arg0) {

                try {

                    System.out.println("getSign===" + arg0.toString());

                    JSONObject json = new JSONObject(arg0);
                    String reason = json.getString("reason");
                    int result = json.getInt("result");
                    String data = json.getString("data");

                    if (result == 1) {
                        signBean = new Gson().fromJson(data,
                                new TypeToken<SignBean>() {
                                }.getType());
                        handler.sendEmptyMessage(1003);
                    }

                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }, new Response.ErrorListener() {

            @Override
            public void onErrorResponse(VolleyError arg0) {
            }
        });
        //为此get请求设置一个Tag属性
        stringRequest.setTag("GET_TAG");
        //将此get请求加入
        requestQueue.add(stringRequest);
    }

    private void commitData() {
        System.out.println("saveSign==" + Contants.saveSign);

        showDialog();
        StringRequest stringRequest = new StringRequest(Request.Method.POST, Contants.saveSign,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        System.out.println("saveSign==" + response);
                        closeDialog();
                        try {
                            JSONObject json = new JSONObject(response);
                            int result = json.getInt("result");
                            String reason = json.getString("reason");

                            if (result == 1) {
                                showToast(reason);
                                finish();
                            } else {
                                showToast(reason);
                            }


                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                closeDialog();
            }
        }) {
            @Override
            protected Map<String, String> getParams() {
                //在这里设置需要post的参数
                Map<String, String> map = new HashMap<String, String>();
                map.put("userid", GlobalData.getUserId(SignActivity.this));
                map.put("address", GlobalData.loc_address);
                map.put("deviceid", Utils.getDeviceId(SignActivity.this));

                System.out.println("mapaddress==" + map.toString());
                return map;
            }
        };
        requestQueue.add(stringRequest);
    }

}
